import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';
import { useModel } from 'umi';
// import FlagImage from '@/components/FlagImage';
// import TagTags from '@/components/TagTags';
import Form from './components/Form';

// import * as c from '@/services/consts';
import * as api from '@/services/serverSupplier';
import { PageContainer } from '@ant-design/pro-components';

const VpnGroupTreeList: React.FC = () => {
  const [formVisible, setFormVisible] = useState<boolean>(false);
  // const [expandedRowKeys, setExpandedRowKeys] = useState<string[]>([]);
  const [current, setCurrent] = useState<API.ServerSupplierModel | undefined>(
    undefined,
  );
  // const [totalConnCount, setTotalConnCount] = useState<number>(0);

  const actionRef = useRef<ActionType>();

  const { hasRight } = useModel('useAuthModel');

  const { reloadServerSuppliers } = useModel('useGlobalModel', (model) => ({
    reloadServerSuppliers: model.reloadServerSuppliers,
  }));

  const loadData = async (
    params: { [key: string]: any },
    sorter?: { [key: string]: any },
    filter?: { [key: string]: any },
  ) => {
    const result = await api.list(params, sorter, filter);

    //console.log(result);
    return Promise.resolve(result);
  };

  const handleFormSubmit = async (record: API.ServerSupplierModel) => {
    let result: API.Result;
    if (current) {
      result = await api.update({
        ...current,
        ...record,
      });
    } else {
      result = await api.add({ ...record });
    }

    if (result && result.success === true) {
      setCurrent(undefined);
      setFormVisible(false);
      actionRef.current?.reload();

      //更新缓存
      await reloadServerSuppliers();
    }
  };

  const handleRemove = async (id: number) => {
    const result = await api.remove({ key: id });
    if (result.success) {
      actionRef.current?.reload();

      //更新缓存
      await reloadServerSuppliers();
    }
  };

  let columns: ProColumns<API.ServerSupplierModel>[] = [
    {
      title: '状态',
      align: 'center',
      width: 80,
      dataIndex: 'status',
      sorter: true,
      valueEnum: {
        true: { status: 'Success', text: '' },
        false: { status: 'Error', text: '' },
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
      sorter: true,
    },
    {
      title: '代码',
      dataIndex: 'code',
      width: 100,
      sorter: true,
    },
    {
      title: '操作代码',
      dataIndex: 'code',
      sorter: true,
      render: (_, record) => {
        return <>
        {record.configs?.changeIpActionCode ? 
        <><h4>更换IP</h4>
        {/* <div>{record.configs?.changeIpActionCode} / {record.configs?.changeIpActionUrl}</div> */}
        </>
        : ''}
        </>
      }
    },
    {
      title: '网址',
      dataIndex: 'url',
      sorter: true,
    },
    // {
    //   title: '服务器',
    //   align: 'center',
    //   dataIndex: 'validServerCount',
    //   sorter: true,
    //   renderText: (_, record) => {
    //     if (record.validServerCount == 0) {
    //       return (
    //         <span style={{ color: '#ff4d4f' }}>
    //           {record.validServerCount}/{record.serverCount}
    //         </span>
    //       );
    //     }
    //     return `${record.validServerCount}/${record.serverCount}`;
    //   },
    // },
    {
      title: '排序',
      align: 'center',
      width: 80,
      dataIndex: 'sort',
      sorter: true,
    },

    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      ellipsis: true,
    },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 180,
      render: (_, record) => {
        let cmps = [];
        if (hasRight('serversupplier_update')) {
          cmps.push(
            <a
              key="edit"
              onClick={(e) => {
                setFormVisible(true);
                setCurrent(record);
              }}
            >
              编辑
            </a>,
          );
        }
        if (hasRight('serversupplier_delete')) {
          cmps.push(
            <Popconfirm
              key="delete"
              title="确定要删除吗?"
              onConfirm={async () => {
                await handleRemove(record.id);
              }}
            >
              <a>删除</a>
            </Popconfirm>,
          );
        }

        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        actionRef={actionRef}
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        search={false}
        pagination={false}
        expandable={
          {
            // defaultExpandAllRows: true,
            // childrenColumnName: 'children',
            // expandRowByClick: true,
            //expandedRowKeys: expandedRowKeys,
          }
        }
        // toolbar={{
        //   filter: (
        //     <>
        //       <Space
        //         style={{
        //           marginRight: '10px',
        //         }}
        //       >
        //         <span>
        //           在线用户合计：<Tag color="#87d068">{totalConnCount}</Tag>
        //         </span>
        //       </Space>
        //     </>
        //   ),
        //   menu: {
        //     type: 'tab',
        //     activeKey: productId,
        //     items: productMenuItems,
        //     onChange: (tabKey) => {
        //       //console.log('tabKey', tabKey);
        //       setProductId(tabKey as string);
        //     },
        //   },
        // }}
        toolBarRender={() => {
          if (hasRight('serversupplier_create')) {
            return [
              <Button
                type="primary"
                key="create"
                onClick={() => {
                  setFormVisible(true);
                }}
              >
                <PlusOutlined /> 新建
              </Button>,
            ];
          }
          return [];
        }}
        columns={columns}
        request={loadData}
      />
      <Form
        visible={formVisible}
        current={current}
        onSubmit={handleFormSubmit}
        onCancel={() => {
          setFormVisible(false);
          setCurrent(undefined);
        }}
      />
    </PageContainer>
  );
};

export default VpnGroupTreeList;
